package com.sy.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sy.auth.mapper.SysRoleMapper;
import com.sy.auth.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sy.auth.service.SysUserRoleService;
import com.sy.model.system.SysRole;
import com.sy.model.system.SysUserRole;
import com.sy.vo.system.AssginRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    SysUserRoleService sysUserRoleService;

    public Map<String, Object> findRolesByUserId(Long userId){
        // 查询所有角色
//        List<SysRole> allRoles = baseMapper.selectList(null);
        List<SysRole> allRoles = this.list();

        // 当前用户所属的角色
        List<SysUserRole> userRoleList = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));

        List<Long> userRoleId = userRoleList.stream().map(sysUserRole -> sysUserRole.getRoleId()).collect(Collectors.toList());

        List<SysRole> roles = allRoles.stream().filter(s -> userRoleId.contains(s.getId())).collect(Collectors.toList());

        // 返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("allRoles", allRoles);
        map.put("roles", roles);
        return map;
    }

    public void doAssign(AssginRoleVo assginRoleVo){
        // 删除已有的角色 根据条件删除
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,
                assginRoleVo.getUserId()));

        // 添加新的角色
        for(Long roleId : assginRoleVo.getRoleIdList()){
            if(StringUtils.isEmpty(roleId)) continue;
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRole.setRoleId(roleId);
            sysUserRoleService.save(sysUserRole);
        }

    }

}